package com.javaweb.dao.impl;

import com.javaweb.dao.CategoryDao;
import com.javaweb.model.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author HLQ
 * @date 2024/10/19 16:00
 */
@Repository
public class CategoryDaoImpl implements CategoryDao {
    @Autowired
    JdbcTemplate jdbcTemplate;
    RowMapper<Category> rowMapper = new RowMapper<Category>() {
        @Override
        public Category mapRow(ResultSet rs, int rowNum) throws SQLException {
            Category category = new Category();
            category.setId(rs.getInt("id"));
            category.setName(rs.getString("name"));
            category.setOrder(rs.getInt("order"));
            category.setParentId(rs.getInt("parent_id"));
            category.setCreateTime(rs.getDate("create_time"));
            category.setUpdateTime(rs.getDate("update_time"));
            return category;
        }
    };
    @Override
    public int insert(Category category){

        String sql = "INSERT INTO tb_category" +
                "(name,`order`,parent_id,create_time,update_time)" +
                "VALUES (?,?,?,?,?)" ;
        Object [] args = new Object[]{
                category.getName(),
                category.getOrder(),
                category.getParentId(),
                new java.sql.Date(category.getCreateTime().getTime()),
                new java.sql.Date(category.getUpdateTime().getTime())};
        return jdbcTemplate.update(sql,args);
    }
    @Override
    public Category select(int categoryId) {
        String sql = "SELECT * FROM tb_category WHERE id=?";
        Object [] args = new Object[]{categoryId};
        return jdbcTemplate.queryForObject(sql,args,rowMapper);
    };
}
